package Demo1;

import java.util.ArrayList;
import java.util.List;

public class BinaryTree {
    static class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    //创建二叉树
    public TreeNode creatTree(){
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(5);
        TreeNode node6 = new TreeNode(6);
        TreeNode node7 = new TreeNode(7);
        TreeNode node8 = new TreeNode(8);
        TreeNode node9 = new TreeNode(9);
        node1.left = node2;
        node1.right = node3;
        node2.left = node4;
        node2.right = node5;
        node3.left = node6;
        node3.right = node7;
        node6.left = node8;
        node8.right = node9;

        return node1;
    }

    //前序遍历
    public void preOrder(TreeNode root){
        if (root == null){
            return;
        }

        System.out.print(root.val + " ");
        preOrder(root.left);
        preOrder(root.right);
    }

    List<Integer> ret = new ArrayList<>();
    public List<Integer> preorderTraversal(TreeNode root) {
        if(root == null) return ret;
        ret.add(root.val);
        preorderTraversal(root.left);
        preorderTraversal(root.right);
        return ret;
    }

    //中序遍历
    public void inOrder(TreeNode root){
        if (root == null){
            return;
        }

        inOrder(root.left);
        System.out.print(root.val + " ");
        inOrder(root.right);
    }


    //后序遍历
    public void postOrder(TreeNode root){
        if (root == null){
            return;
        }

        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val + " ");
    }
}

class Main2{
    public static void main(String[] args) {
        BinaryTree test = new BinaryTree();
        BinaryTree.TreeNode root = test.creatTree();
/*        test.preOrder(root);
        List<Integer> ret = test.preorderTraversal(root);
        System.out.println(ret);*/
        test.inOrder(root);
        System.out.println();
        test.postOrder(root);
    }
}
